package com.test.manager;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author ssang
 * @date 2022-02-11 16:14
 */
@Slf4j
@Component
public class AliMqttSendService {
    @Autowired
    Producer mqttProducer;

    /**
     * 发送消息
     * @param topic
     * @param tag
     * @param msg
     * @return
     */
    public boolean sendMqttMsg(String topic, String tag, String msg){
        log.info("发送mqtt消息 topic:{} tag:{} msg:{}", topic, tag, msg);

        Message message = new Message(topic, tag, msg.getBytes(StandardCharsets.UTF_8));

        try {
//            mqttProducer.sendOneway(message);
            SendResult result = mqttProducer.send(message);
            log.info("msgId:{}",result.getMessageId());
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
